package util;

import java.util.Date;
import java.util.Random;

import com.tudou.itemcodecrypt.CryptException;
import com.tudou.itemcodecrypt.ItemCodeCrypt;
import common.Constant;

public class KeyGen {

	/**
	 * @param args
	 */

	public static String getKey(int id) {
		String key = "";
		String n = String.valueOf((new Date().getTime()) + new Random().nextInt(999)).substring(4);
		try {
			key = ItemCodeCrypt.getCode(Integer.valueOf(n)) + ItemCodeCrypt.getCode(id) + Md5encode.getMD5ofStr(n).substring(22).toUpperCase();

		} catch (CryptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return key;
	}

	public static String getId(String key) {
		String id = null;
		try {
			id = String.valueOf(ItemCodeCrypt.getItemId(key.substring(11, 22)));
		} catch (CryptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return id;
	}

	public static int getTimeDiff(String key) {
		int keytime = 0;
		int now = Integer.valueOf(String.valueOf((new Date().getTime())).substring(4));

		try {
			keytime = (int) ItemCodeCrypt.getItemId(key.substring(0, 11));
		} catch (CryptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		return now - keytime;
	}

	public static boolean cookieValid(String key) {

		if (null == key || key.length() != 32)
			return false;
		try {
			int diff = getTimeDiff(key) / 1000;
			if (diff < 0 || diff > Constant.CookieExpired)
				return false;
			int id = Integer.valueOf(getId(key));
			if (id < 0 || id > 10000000)
				return false;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static String convertId2Code(int id) {
		String code = "";
		try {
			code = ItemCodeCrypt.getCode(id);
		} catch (CryptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return code;
	}

	public static int convertCode2Id(String code) {
		int id = 0;
		try {
			id = (int) ItemCodeCrypt.getItemId(code);
		} catch (CryptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return id;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		System.out.println(new Date().getTime());
		String key = getKey(1963285767);
		System.out.println(key);
		System.out.println(convertCode2Id("7QnN4aUNmo0"));
		System.out.println(convertId2Code(1));
		System.out.println(getId("9a1b7m_TJm8jzr13FqdpLkE3C28AB8D3"));

		System.out.println(getTimeDiff("ynm-CHf13sAwHXXw3U0CeoDEB42865BB"));
		System.out.println(cookieValid("ynm-CHf13sAwHXXw3U0CeoDEB42865BB"));
	}

}
